package com.it.web.action;

import java.io.IOException;
import java.util.concurrent.TimeUnit;

import javax.jms.JMSException;
import javax.jms.MapMessage;
import javax.jms.Message;
import javax.jms.Session;
import javax.ws.rs.Consumes;
import javax.ws.rs.core.MediaType;

import org.apache.commons.lang.RandomStringUtils;
import org.apache.cxf.jaxrs.client.WebClient;
import org.apache.struts2.ServletActionContext;
import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Namespace;
import org.apache.struts2.convention.annotation.ParentPackage;
import org.apache.struts2.convention.annotation.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Scope;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.jms.core.JmsTemplate;
import org.springframework.jms.core.MessageCreator;
import org.springframework.stereotype.Controller;

import com.it.util.MailUtils;

import cn.itcast.bos.domain.delivery.Constants;
import cn.itcast.crm.domain.Customer;

@ParentPackage("json-default")
@Namespace("/")
@Controller
@Scope("prototype")
@SuppressWarnings("all")
public class CustomerAction extends BaseAction<Customer>{
	private static final long serialVersionUID = 1L;
	
	@Autowired
	@Qualifier("jmsQueueTemplate")
	private JmsTemplate jmsTemplate;
	
	@Autowired
	private RedisTemplate<String, String> redisTemplate;
	
	private String checkcode;
	
	public void setCheckcode(String checkcode) {
		this.checkcode = checkcode;
	}

	@Action(value="customer_regist", results={@Result(name="success", type="redirect", location="signup-success.html"),
			@Result(name="input", type="redirect", location="signup.html")})
	public String regist() {
		System.out.println(tel);
		String dataInSession = (String) ServletActionContext.getRequest().getSession().getAttribute(model.getTelephone());
		System.out.println(dataInSession + ":" + checkcode);
		if ("".equals(dataInSession.trim()) || dataInSession == null || !dataInSession.equals(checkcode)) {
			System.out.println("验证失败");
			return INPUT;
		}
		WebClient.create("http://localhost:9002/crm_management/services/customerService"
				+ "/customer").type(MediaType.APPLICATION_JSON).post(model);
		
		System.out.println("客户注册成功...");
		
		//生成激活码
		String activecode = RandomStringUtils.randomNumeric(32);
		
		//将激活码保存在24小时失效的redis中
		redisTemplate.opsForValue().set(model.getTelephone(), activecode, 24, TimeUnit.HOURS);
		String content = "尊敬的客户您好，请于24小时内，进行邮箱账户的绑定，点击下面地址完成绑定:<br/><a href='"
				+ MailUtils.activeUrl + "?telephone=" + model.getTelephone()
				+ "&activecode=" + activecode + "'>速运快递邮箱绑定地址</a>";
		MailUtils.sendMail("速运快递激活邮件", content, model.getEmail());
		return SUCCESS;
	}
	
	private static String tel;
	
	public void setTel(String tel) {
		this.tel = tel;
	}

	@Action(value="customer_sendSms")
	public String sendSms() {
		//手机号保存在Customer对象
		//生成验证码
		System.out.println("++++++++++++++++" + tel);
		String randomCode = RandomStringUtils.randomNumeric(4);
		ServletActionContext.getRequest().getSession().setAttribute(tel, randomCode);
		System.out.println("手机验证码是:" + randomCode);
		
		//这里写手机短信的代码,这里就不写了
		//TODO		
		System.out.println("模拟发短信");
		final String msg = "尊敬客户，你的验证码是:" + randomCode + "服务电话:123";
		jmsTemplate.send("bos_sms", new MessageCreator() {
			
			@Override
			public Message createMessage(Session session) throws JMSException {
				MapMessage mapMessage = session.createMapMessage();
				mapMessage.setString("telephone", model.getTelephone());
				mapMessage.setString("msg", msg);
				return mapMessage;
			}
		});
		return NONE;
	}
	
	@Action("customer_activeMail")
	public String activeMail() {
		ServletActionContext.getResponse().setContentType("text/html;charset=UTF-8");
		
		String activecodeRedis = redisTemplate.opsForValue().get(model.getTelephone());
		if (activecodeRedis == null) {
			try {
				ServletActionContext.getResponse().getWriter().println("激活无效，请重新注册");
			} catch (IOException e) {
				e.printStackTrace();
			}
		} else {
			Customer customer = WebClient.create("http://localhost:9002/crm_management/services/customerService"
					+ "/customer/telephone/" + model.getTelephone())
					.accept(MediaType.APPLICATION_JSON).get(Customer.class);
			System.out.println("c:"+customer);
			if (customer.getType() == null || customer.getType() != 1){
				System.out.println("--------------------4");
				//没有绑定
				WebClient.create("http://localhost:9002/crm_management/services/customerService"
					+ "/customer/updatetype/" + model.getTelephone()).put(null);
				try {
					ServletActionContext.getResponse().getWriter().println("邮箱绑定成功");
				} catch (IOException e) {
					 e.printStackTrace();
				}
			} else {
				System.out.println("---------------------------5");
				try {
					ServletActionContext.getResponse().getWriter().println("该邮箱已绑定，无需重复绑定");
				} catch (IOException e) {
					 e.printStackTrace();
				}
			}
			//删除redis激活码
			redisTemplate.delete(model.getTelephone());
		}
		return null;
	}
	
	@Action(value="customer_login", results={@Result(name="error", location="login.html", type="redirect"), 
			@Result(name="success", location="index.html#/myhome", type="redirect")})
	public String lotgin() {
		Customer customer = WebClient.create("http://localhost:9002/crm_management/services/customerService"
				+ "/customer/login?telephone=" + model.getTelephone() + "&password="
				+ model.getPassword()).accept(MediaType.APPLICATION_JSON).get(Customer.class);
		if (customer == null) {
			return ERROR;
		}
		
		//登陆成功
		ServletActionContext.getRequest().getSession().setAttribute("customer", customer);
		return SUCCESS;
	}
}
